#include "fescalelayout_private.h"
#include <QtGui>

FeScaleLayout::FeScaleLayout(const QSize &_baseSize)
{
	baseSize = _baseSize;
}

FeScaleLayout::FeScaleLayout(const QSize &_baseSize, QWidget *parent)
	: QLayout(parent)
{
	baseSize = _baseSize;
}

FeScaleLayout::~FeScaleLayout()
{
	QLayoutItem *l;
    while ((l = takeAt(0)))
        delete l;
}


void FeScaleLayout::addItem(QLayoutItem *item)
{
	add(item, item->geometry());
}

void FeScaleLayout::addWidget(QWidget *widget, const QRect &rect)
{
	add(new QWidgetItem(widget), rect);
}

Qt::Orientations FeScaleLayout::expandingDirections() const
{
	return Qt::Horizontal | Qt::Vertical;
}

bool FeScaleLayout::hasHeightForWidth() const
{
	return false;
}

int FeScaleLayout::count() const
{
	return list.size();
}

QSize FeScaleLayout::minimumSize() const
{
	// TODO
	return QSize(0,0);
}

void FeScaleLayout::setGeometry(const QRect &rect)
{
	QLayout::setGeometry(rect);

#ifdef FESCALELAYOUT_DEBUG
	{
		qDebug("set geometry %d,%d,%d,%d",
			rect.x(), rect.y(), rect.width(), rect.height());
	}
#endif

	int i;
    int base_w = baseSize.width();
	int base_h = baseSize.height();

	int rect_x = rect.x();
	int rect_y = rect.y();
	int rect_w = rect.width();
	int rect_h = rect.height();

    for (i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QLayoutItem *item = wrapper->item;
		const QRect &i_rect = wrapper->rect;

		int x = rect_x + i_rect.x() * rect_w / base_w;
		int y = rect_y + i_rect.y() * rect_h / base_h;
		int w = (i_rect.x() + i_rect.width()) * rect_w / base_w - (x - rect_x);
		int h = (i_rect.y() + i_rect.height()) * rect_h / base_h - (y - rect_y);

		item->setGeometry(QRect(x, y, w, h));

#ifdef FESCALELAYOUT_DEBUG
		{
			QWidget *wg = item->widget();
			if(wg)
			{
				QByteArray name = wg->objectName().toLatin1();
				qDebug("layout widget %s %d,%d,%d,%d -> %d,%d,%d,%d",
					name.constData(),
					x, y, w, h,
					wg->x(), wg->y(), wg->width(), wg->height());
			}
		}
#endif
	}
}

QSize FeScaleLayout::sizeHint() const
{
	return baseSize;
}

QLayoutItem *FeScaleLayout::itemAt(int index) const
{
	ItemWrapper *wrapper = list.value(index);
    if (wrapper)
        return wrapper->item;
    else
        return 0;
}

QLayoutItem *FeScaleLayout::takeAt(int index)
{
	if (index >= 0 && index < list.size()) {
        ItemWrapper *layoutStruct = list.takeAt(index);
        return layoutStruct->item;
    }
    return 0;
}

void FeScaleLayout::add(QLayoutItem *item, const QRect &rect)
{
#ifdef FESCALELAYOUT_DEBUG
	{
		QWidget *w = item->widget();
		if(w)
		{
			QByteArray name = w->objectName().toLatin1();
			qDebug("add layout item %s %d,%d,%d,%d",
				name.constData(),
				rect.x(),
				rect.y(),
				rect.width(),
				rect.height());
		}
	}
#endif
	list.append(new ItemWrapper(item, rect));
}

